package org.aom.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import javax.faces.context.FacesContext;
import javax.faces.convert.DateTimeConverter;

import org.operamasks.faces.annotation.Convert;
import org.operamasks.faces.annotation.DefineConverter;
import org.operamasks.faces.annotation.Format;
import org.operamasks.faces.component.layout.UIFacelet;

@DefineConverter(id="outputDateFormatter")
public class DateFormatter {
	@Format
    public String format(Object value) {
        if (value instanceof Date) {
            SimpleDateFormat formatter = (SimpleDateFormat) SimpleDateFormat.getInstance();
            formatter.applyPattern("yy-M-d");
            formatter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
            return formatter.format(value);
        }
        return value == null ? "" : value.toString();
    }
    
    @Convert
    public Object convert(String value) {
        FacesContext context = FacesContext.getCurrentInstance();
        DateTimeConverter converter = (DateTimeConverter)context.getApplication().createConverter(DateTimeConverter.CONVERTER_ID);
        converter.setPattern("yyyy-MM-dd");
        converter.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        return converter.getAsObject(context, new UIFacelet(), value);
    }
}
